package com.qijian.common.utils;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.math.BigDecimal;
import java.util.Date;

/**
 *  @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
public class JsonUtils {
  private static final ObjectMapper JSON = new ObjectMapper();

  static {
    JSON.setSerializationInclusion(Include.NON_NULL);
    JSON.configure(SerializationFeature.INDENT_OUTPUT, Boolean.TRUE);
  }

  public static String toJson(Object obj) {
    try {
      return JSON.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }

    return null;
  }

  public static Date getDateFromSpecData(JSONObject data, String field, int index) {
    JSONObject jsonObject = data.getJSONObject(field);
    if (null == jsonObject) {
      return null;
    }
    JSONArray arr = jsonObject.getJSONArray("specialobj");
    if (null == arr || arr.size() == 0) {
      return null;
    }
    JSONObject obj = arr.getJSONObject(index);
    return obj.getDate("name");
  }

  public static String getStrFromSpecData(JSONObject data, String field, int index) {
    JSONObject jsonObject = data.getJSONObject(field);
    if (null == jsonObject) {
      return null;
    }
    JSONArray arr = jsonObject.getJSONArray("specialobj");
    if (null == arr || arr.size() == 0) {
      return null;
    }

    JSONObject obj = arr.getJSONObject(index);
    return obj.getStr("name");
  }

  public static BigDecimal getDecimalFromData(JSONObject data, String field) {
    JSONObject jsonObject = data.getJSONObject(field);
    if (null == jsonObject) {
      return null;
    }
    return jsonObject.getBigDecimal("value");
  }


  public static Date getDateFromData(JSONObject data, String field) {
    JSONObject jsonObject = data.getJSONObject(field);
    if (null == jsonObject) {
      return null;
    }
    return jsonObject.getDate("value");
  }

  public static String getStrFromData(JSONObject data, String field) {
    JSONObject jsonObject = data.getJSONObject(field);
    if (null == jsonObject) {
      return null;
    }
    return jsonObject.getStr("value");
  }
}
